<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//define("APPID", "wx5672506691fea394"); //appid值
//define("APPSECRET", "a10b06bf4f7519152bad03311f212e65"); //密钥

class ContactOnline extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Onduty_Model');
		$this->load->model('Access_Token_Model');
		$this->load->model('Conversation_Model');
		$this->load->model('Users_Model');
		$this->load->helper('url_helper');
		$this->load->library('session');
		$this->load->library('HttpPost');
		$this->load->library('SignatureClass');
		$this->load->library('AccessTokenClass');
		$this->load->library('Vars');
	}
	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 *        http://example.com/index.php/welcome
	 *    - or -
	 *        http://example.com/index.php/welcome/index
	 *    - or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function onlinelist()
	{
		$server_list=$this->Onduty_Model->get_excute_server_list();
		$data=array('title'=>'执行举报');
		$data['server_list']=$server_list;
		$this->load->view('head_sec',$data);
		$this->load->view('online_service_list',$data);
		$this->load->view('foot_sec',$data);
	}

	public function askerlist(){
		if(empty($this->session->userdata('user'))){
			$uri=$this->uri->uri_string();
			$array=array('uri'=>$uri);
			$this->session->set_userdata($array);
			header("Location:/index.php/UserInfoAuth/auth");
		}
		$user=$this->session->userdata('user');
		$openid=$user['openid'];
		$data['openid']=$openid;
		$server=$this->Onduty_Model->get_onduty_by_param($data);
		$server_id=$server[0]['id'];
		$asker_list=$this->get_asker_openid_list_by_server_openid($openid);
		$data=array('title'=>'执行举报');
		$data['server_id']=$server_id;
		$data['asker_list']=$asker_list;
		$this->load->view('head_sec',$data);
		$this->load->view('asker_list',$data);
		$this->load->view('foot_sec',$data);
	}

	public function get_asker_openid_list_by_server_openid($openid){
		$asker_openid_list=$this->Conversation_Model->get_asker_openid_list($openid);
		$asker_list=array();
		foreach($asker_openid_list as $row):
			$asker=$this->Users_Model->get_user_by_openid($row['asker_openid']);
			array_push($asker_list,$asker);
		endforeach;
		return $asker_list;
	}

	public function save(){
		$content=$this->input->post('content');
		$asker_openid=$this->input->post('asker_openid');
		$server_openid=$this->input->post('server_openid');
		$name=$this->input->post('name');
		$headimgurl=$this->input->post('headimgurl');
		$direction=$this->input->post('direction');
		$serverid=$this->input->post('serverid');
		$askerid=$this->input->post('askerid');
		$data=array(
			'content'=>$content,
			'asker_openid'=>$asker_openid,
			'server_openid'=>$server_openid,
			'name'=>$name,
			'headimgurl'=>$headimgurl,
			'direction'=>$direction,
			'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
			'gmt_create'=>date("Y-m-d H:i:s" ,time()),
			'is_deleted'=>'N'
		);
		$result=$this->Conversation_Model->addConversation($data);
		$resp='';
		if($direction==0){
			$resp=$this->sendNoticeToUser($direction,$server_openid,$serverid,$askerid);
		}else{
			$resp=$this->sendNoticeToUser($direction,$asker_openid,$serverid,$askerid);
		}
		if($result){
			header('content-type:application:json;charset=utf8');
			header('Access-Control-Allow-Origin:*');
			header('Access-Control-Allow-Methods:POST');
			header('Access-Control-Allow-Headers:x-requested-with,content-type');
			$result = array();
			$result['isSuccess'] = true;
			$result['errorMessage'] = '';
			$result['data'] = $resp;
			echo json_encode($result, JSON_UNESCAPED_UNICODE);
		}else{
			header('content-type:application:json;charset=utf8');
			header('Access-Control-Allow-Origin:*');
			header('Access-Control-Allow-Methods:POST');
			header('Access-Control-Allow-Headers:x-requested-with,content-type');
			$result = array();
			$result['isSuccess'] = false;
			$result['errorMessage'] = '发送消息失败';
			$result['data'] = $resp;
			echo json_encode($result, JSON_UNESCAPED_UNICODE);
		}
	}

	private function sendNoticeToUser($direction,$openid,$serverid,$askerid){
		$access_token=$this->accesstokenclass->get_access_token();
		$url='https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
		$timeout = 40;
		$data['touser']=$openid;
		$data['template_id']='ADKQCR8LKBJ1nTslMgjJZN4e1yKeIeM0Ie5sqogy0WY';
		$data["topcolor"]="#FF0000";
		$first_value='';
		$kw2_value='';
		$url1='';
		if($direction==0){
			$url1='http://www.fddiaoyu.com/index.php/contactonline/conversation/'.$serverid.'/'.$askerid.'/server';
			$first_value='新咨询提示';
			$kw2_value='您有新的咨询，请点击详情查看！';
		}else{
			$url1='http://www.fddiaoyu.com/index.php/contactonline/conversation/'.$serverid.'/'.$askerid.'/asker';
			$first_value='新回复提示';

			$kw2_value='您的咨询有新的回复了，请点击详情查看！';
		}
		$data["url"]=$url1;
		$first['value']=$first_value;
		$first['color']='#1196EE';
		$keyword1['value']=date("Y-m-d H:i:s" ,time());
		$keyword1['color']='#1196EE';
		$keyword2['value']=$kw2_value;
		$keyword2['color']='#1196EE';
		$remark['value']='';
		$remark['color']='#1196EE';
		$body['first']=$first;
		$body['keyword1']=$keyword1;
		$body['keyword2']=$keyword2;
		$body['remark']=$remark;
		$data['data']=$body;
		$data1=json_encode($data);
	//	print_r($data1);
		$response=$this->httppost->post($url,$data1,$timeout);
		return $response;

	}

	public function conversation($serverid=1,$askerid=0,$role='asker'){
		$uri= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$array=array('uri'=>$uri);
		$this->session->set_userdata($array);
		$data=$this->signatureclass->generate_signature();
		$varriable=$this->vars->get_constants();
		$data['APPID']=$varriable['APPID'];
		$server=$this->Onduty_Model->get_excute_server_by_id($serverid);

		$realname=$server->realname;
		$server_openid=$server->openid;
		if(empty($this->session->userdata('user'))){
			$array=array('uri'=>$uri);
			$this->session->set_userdata($array);
			header("Location:/index.php/UserInfoAuth/auth");
		}
		$curruser=$this->session->userdata('user');
		$asker_openid='';
		if($askerid==0){
			$asker_openid=$curruser['openid'];
			$askerid=$this->get_userid_by_openid($asker_openid);
		}else{
			$asker_openid=$this->get_openid_by_userid($askerid);
		}

		$param['asker_openid']=$asker_openid;
		$param['server_openid']=$server_openid;

		$convers=$this->Conversation_Model->get_conversation_list($param);
		$data['conversations']=$convers;
		$data['role']=$role;

		$data['curruser']=$curruser;
		$data['title']=$realname;
		if($role=='asker'){
			$data['name']=$curruser['nickname'];
			$asker_openid=$curruser['openid'];
		}else{
			$data['name']=$realname;
			$data['title']=$curruser['nickname'];
			//$asker_openid=$curruser['openid'];
		}
		$data['asker_openid']=$asker_openid;
		$data['server_openid']=$server_openid;
		$data['serverid']=$serverid;
		$data['askerid']=$askerid;
		$data['headimgurl']=$curruser['headimgurl'];

		$this->load->view('head_sec',$data);
		$this->load->view('conversation',$data);
		$this->load->view('foot_sec',$data);
	}

	public function get_userid_by_openid($openid){
		$data['openid']=$openid;
		$users=$this->Users_Model->get_users($data);

		if(!empty($users)&& count($users)>0){
			return $users[0]['id'];
		}else{
			return 0;
		}
	}

	public function get_openid_by_userid($userid){
		$user=$this->Users_Model->get_user_by_id($userid);
		return $user['openid'];
	}

	public function get_access_token(){
		$access_token_array=$this->Access_Token_Model->get_sys_access_token();
		if(empty($access_token_array)||count($access_token_array)==0){
			$accessToken=$this->get_new_access_token();
			$data=array(
				'gmt_create'=>date("Y-m-d H:i:s" ,time()),
				'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
				'token_type'=>'1',
				'expire_time'=>date("Y-m-d H:i:s" ,time()+7200),
				'access_tokens'=>$accessToken
			);
			$result=$this->Access_Token_Model->insert_access_token($data);
			if($result){
				return $accessToken;
			}else{
				return "";
			}
		}else{
			$access_token_row=$access_token_array[0];
			$expire_time=$access_token_row['expire_time'];
			//echo  'expire_time is:'.$expire_time;
			if(strtotime($expire_time)<time()){
				$this->expire_access_token();

			}else{
				return $access_token_row['access_tokens'];
			}
		}
	}

	public function get_new_access_token(){
		$token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
		$res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
//echo $res;
		$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
		$access_token = $result['access_token'];
		return $access_token;
	}
	public function  expire_access_token(){
		$access_token=$this->get_new_access_token();
		$access_token_array=$this->Access_Token_Model->get_sys_access_token();
		$access_token_row=$access_token_array[0];
		if(!isset($access_token_row)){
			return false;
		}
		$data=array(
			'id'=>$access_token_row['id'],
			'gmt_modify'=>date("Y-m-d H:i:s" ,time()),
			'expire_time'=>date("Y-m-d H:i:s" ,time()+7200),
			'access_tokens'=>$access_token
		);

		$result=$this->Access_Token_Model->update_access_token($data);
		if($result){
			return true;
			$access_token_row['access_tokens'];
		}else{
			return false;
		}
	}
}


